package com.example.trafficsystem.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.example.trafficsystem.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class OssService {
    @Autowired
    private OssConfig ossConfig;

    private OSS getOSSClient() {
        return new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
    };
    /**
     * 获取文件列表
     * @param folderName OSS 中的文件夹路径（如果不需要区分文件夹，可传空字符串）
     * @return 文件名列表
     */
    public List<String> listObjects(String folderName) {
       OSS ossClient = getOSSClient();
       try {
           return ossClient.listObjects(ossConfig.getBucketName()).getObjectSummaries()
                   .stream().
                   map(OSSObjectSummary::getKey)
                   .collect(Collectors.toList());
       }finally {
           ossClient.shutdown();
       }
    }
    public String getUrl(String fileName){
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;

    }
}
